<?php
	if(isset($_SESSION['loggedin']) || isset($_COOKIE['loggedin'])) {
		header("Location: ".HTTP_SERVER.ADMIN_DIR."index");
		exit;
	}
		
	$forgot = (isset($url[1]))?$url[1]:'';
	
	if(isset($_POST['submit'])) {
		if($forgot!='forgot') $msg = checkLogin($_POST['user'], $_POST['pass'], $_POST['enablecookies']);
		else $msg = send_forgot_pwd($_POST['user'], $_POST['email']);
		$post_username = $_POST['user'];
		$post_password = $_POST['pass'];
		$post_cookies = $_POST['enablecookies'];
		//if executing via ajax, return results
		if(isset($_GET['ajax'])) {
			echo $msg;
			exit;
		}
		if(!$msg) { //no problems. redirect them to the login section
			header("Location: ".HTTP_SERVER.ADMIN_DIR."index");
			exit;
		}
	}
	
	function checkLogin($user, $pw, $cookies) {
		$db = new CDatabase();
		$db->Connect();
		$db->Query("SELECT password, email, access FROM member WHERE username = '" . $user . "'");
		if($db->getRow()) {
			if(strcmp($db->access['password'], crypt($pw, SALT)) == 0) {
				$_SESSION['loggedin'] = $user;
				$_SESSION['email'] = $db->access['email'];
				$_SESSION['access'] = $db->access['access'];
				if($cookies==1) setcookie("loggedin", $user, mktime()+1209600, HTTP_COOKIE_PATH, HTTP_COOKIE_DOMAIN);
				return false;
			} else return "<span class='error'>Incorrect Password</span>";
		} else return "<span class='error'>Incorrect Username</span>";
	}
	
	function send_forgot_pwd($user, $email) {
		$db = new CDatabase();
		$db->Connect();
		//generate new password
		$chars = "abchefghjkmnpqrstuvwxyz0123456789";
		srand((double)microtime()*1000000);
		$i = 0;
		while ($i <= 7) {
			$num = rand() % 33;
			$tmp = substr($chars, $num, 1);
			$new_pwd = $new_pwd . $tmp;
			$i++;
		}
		$crypt_pwd = crypt($new_pwd, SALT);

		//capture/update new password
		$db->Query("UPDATE member SET password='$crypt_pwd' WHERE username='$user'");
		//send new password
		$subject = CONTEST_NAME.": New Login Password";
		$message = "Hello $user,\n\n".
							"You are receiving this email because you have requested a new password be sent to you in order to login to ".CONTEST_NAME.".\n\n".
							"Here it is below.\n".
							"------------------\n".
							"Username: $user\n".
							"Password: $new_pwd\n".
							"-------------------\n\n".
							"You may login at the website address below:\n".
							HTTP_SERVERPATH."login\n\n".
							"You can of course change this password yourself once logged in.\n\n".
							"Thanks\n";
		mail($email,$subject,$message, "From: ".CONTEST_NAME." <".MASTER_EMAIL.">\r\n");
		return "<span clas='success'>Your new password has been emailed to your email address.</span>";
	}
	
?>